import { Request, Response } from 'express';
import { User } from '@/models/User';
import { Car } from '@/models/Vehicle';
import { generateToken } from '@/config/jwt';
import { UserRole } from '@/types';
import { AuthenticatedRequest } from '@/middleware/auth';

/**
 * @swagger
 * /api/auth/register:
 *   post:
 *     summary: 用户注册
 *     tags: [认证]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - username
 *               - email
 *               - password
 *             properties:
 *               username:
 *                 type: string
 *                 description: 用户名
 *               email:
 *                 type: string
 *                 description: 邮箱
 *               password:
 *                 type: string
 *                 description: 密码
 *     responses:
 *       201:
 *         description: 注册成功
 *       400:
 *         description: 请求参数错误
 */
export const register = async (req: Request, res: Response): Promise<void> => {
  try {
    const { username, email, password, nickname } = req.body;

    // 检查用户是否已存在
    const existingUser = await User.findOne({
      $or: [{ email }, { username }],
    });

    if (existingUser) {
      res.status(400).json({
        success: false,
        message: '用户名或邮箱已存在',
      });
      return;
    }

    // 如果没有提供email，使用username@autocost.local作为默认邮箱
    const userEmail = email || `${username}@autocost.local`;

    // 创建新用户
    const user = new User({
      username,
      email: userEmail,
      password,
      role: UserRole.USER,
      nickname,
    });

    await user.save();

    // 生成JWT令牌
    const token = generateToken(user._id.toString(), user.username, user.role);

    res.status(201).json({
      success: true,
      message: '注册成功',
      data: {
        user: {
          id: user._id,
          username: user.username,
          email: user.email,
          role: user.role,
          nickname: user.nickname,
        },
        token,
      },
    });
  } catch (error) {
    console.error('注册错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误',
    });
  }
};

/**
 * @swagger
 * /api/auth/login:
 *   post:
 *     summary: 用户登录
 *     tags: [认证]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - password
 *             properties:
 *               username:
 *                 type: string
 *                 description: 用户名
 *               email:
 *                 type: string
 *                 description: 邮箱
 *               password:
 *                 type: string
 *                 description: 密码
 *     responses:
 *       200:
 *         description: 登录成功
 *       400:
 *         description: 请求参数错误
 *       401:
 *         description: 认证失败
 */
export const login = async (req: Request, res: Response): Promise<void> => {
  try {
    const { username, email, password } = req.body;

    if (!password) {
      res.status(400).json({
        success: false,
        message: '密码不能为空',
      });
      return;
    }

    if (!username && !email) {
      res.status(400).json({
        success: false,
        message: '用户名或邮箱不能为空',
      });
      return;
    }

    // 构建查询条件
    let query: any = {};
    if (username) {
      query.username = username;
    } else if (email) {
      query.email = email;
    }

    // 查找用户
    const user = await User.findOne(query);

    if (!user) {
      res.status(401).json({
        success: false,
        message: '用户名/邮箱或密码错误',
      });
      return;
    }

    // 验证密码
    const isPasswordValid = await user.comparePassword(password);
    if (!isPasswordValid) {
      res.status(401).json({
        success: false,
        message: '用户名/邮箱或密码错误',
      });
      return;
    }

    // 生成JWT令牌
    const token = generateToken(user._id.toString(), user.username, user.role);

    res.status(200).json({
      success: true,
      message: '登录成功',
      data: {
        user: {
          id: user._id,
          username: user.username,
          email: user.email,
          role: user.role,
          nickname: user.nickname,
        },
        token,
      },
    });
  } catch (error) {
    console.error('登录错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误',
    });
  }
};

/**
 * @swagger
 * /api/auth/profile:
 *   get:
 *     summary: 获取用户信息
 *     tags: [用户]
 *     security:
 *       - bearerAuth: []
 *     responses:
 *       200:
 *         description: 获取成功
 *       401:
 *         description: 未授权
 */
export const getProfile = async (
  req: AuthenticatedRequest,
  res: Response
): Promise<void> => {
  try {
    const user = await User.findById(req.userId).select('-password');

    if (!user) {
      res.status(404).json({
        success: false,
        message: '用户不存在',
      });
      return;
    }

    res.status(200).json({
      success: true,
      message: '获取用户信息成功',
      data: user,
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '服务器内部错误',
    });
  }
};

/**
 * @swagger
 * /api/auth/profile:
 *   put:
 *     summary: 更新用户信息
 *     tags: [用户]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               username:
 *                 type: string
 *                 description: 用户名
 *               email:
 *                 type: string
 *                 description: 邮箱
 *     responses:
 *       200:
 *         description: 更新成功
 *       401:
 *         description: 未授权
 */
export const updateProfile = async (
  req: AuthenticatedRequest,
  res: Response
): Promise<void> => {
  try {
    const { username, email } = req.body;
    const updateData: any = {};

    if (username) updateData.username = username;
    if (email) updateData.email = email;

    const user = await User.findByIdAndUpdate(req.userId, updateData, {
      new: true,
      runValidators: true,
    }).select('-password');

    if (!user) {
      res.status(404).json({
        success: false,
        message: '用户不存在',
      });
      return;
    }

    res.status(200).json({
      success: true,
      message: '更新用户信息成功',
      data: user,
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '服务器内部错误',
    });
  }
};

/**
 * @swagger
 * /api/auth/change-password:
 *   put:
 *     summary: 修改密码
 *     tags: [用户]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - currentPassword
 *               - newPassword
 *             properties:
 *               currentPassword:
 *                 type: string
 *                 description: 当前密码
 *               newPassword:
 *                 type: string
 *                 description: 新密码
 *     responses:
 *       200:
 *         description: 修改成功
 *       401:
 *         description: 当前密码错误
 */
export const changePassword = async (
  req: AuthenticatedRequest,
  res: Response
): Promise<void> => {
  try {
    const { currentPassword, newPassword } = req.body;

    const user = await User.findById(req.userId);
    if (!user) {
      res.status(404).json({
        success: false,
        message: '用户不存在',
      });
      return;
    }

    // 验证当前密码
    const isCurrentPasswordValid = await user.comparePassword(currentPassword);
    if (!isCurrentPasswordValid) {
      res.status(401).json({
        success: false,
        message: '当前密码错误',
      });
      return;
    }

    // 更新密码
    user.password = newPassword;
    await user.save();

    res.status(200).json({
      success: true,
      message: '密码修改成功',
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '服务器内部错误',
    });
  }
};

/**
 * @swagger
 * /api/auth/delete:
 *   delete:
 *     summary: 删除用户
 *     tags: [用户]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - password
 *             properties:
 *               password:
 *                 type: string
 *                 description: 用户密码（确认删除）
 *     responses:
 *       200:
 *         description: 删除成功
 *       401:
 *         description: 密码错误或未授权
 */
export const deleteUser = async (
  req: AuthenticatedRequest,
  res: Response
): Promise<void> => {
  try {
    const { password } = req.body;

    if (!password) {
      res.status(400).json({
        success: false,
        message: '请输入密码确认删除',
      });
      return;
    }

    const user = await User.findById(req.userId);
    if (!user) {
      res.status(404).json({
        success: false,
        message: '用户不存在',
      });
      return;
    }

    // 验证密码
    const isPasswordValid = await user.comparePassword(password);
    if (!isPasswordValid) {
      res.status(401).json({
        success: false,
        message: '密码错误',
      });
      return;
    }

    // 删除用户
    await User.findByIdAndDelete(req.userId);

    res.status(200).json({
      success: true,
      message: '用户删除成功',
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '服务器内部错误',
    });
  }
};

/**
 * @swagger
 * /api/auth/set-default-vehicle:
 *   put:
 *     summary: 设置默认车辆
 *     tags: [用户]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - vehicleId
 *             properties:
 *               vehicleId:
 *                 type: string
 *                 description: 车辆ID
 *     responses:
 *       200:
 *         description: 设置成功
 *       400:
 *         description: 请求参数错误
 *       404:
 *         description: 车辆不存在
 */
export const setDefaultVehicle = async (
  req: AuthenticatedRequest,
  res: Response
): Promise<void> => {
  try {
    const { vehicleId } = req.body;

    if (!vehicleId) {
      res.status(400).json({
        success: false,
        message: '车辆ID是必需的',
      });
      return;
    }

    // 验证车辆是否存在且属于当前用户
    const vehicle = await Car.findOne({
      _id: vehicleId,
      userId: req.userId,
    });

    if (!vehicle) {
      res.status(404).json({
        success: false,
        message: '车辆不存在或无权限访问',
      });
      return;
    }

    // 更新用户的默认车辆
    const user = await User.findByIdAndUpdate(
      req.userId,
      { defaultVehicleId: vehicleId },
      { new: true }
    );

    if (!user) {
      res.status(404).json({
        success: false,
        message: '用户不存在',
      });
      return;
    }

    res.status(200).json({
      success: true,
      message: '默认车辆设置成功',
      data: {
        defaultVehicleId: vehicleId,
        vehicle: {
          id: vehicle._id,
          name: vehicle.name,
          brand: vehicle.brand,
          carModel: vehicle.carModel,
          licensePlate: vehicle.licensePlate,
        },
      },
    });
  } catch (error) {
    console.error('设置默认车辆错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误',
    });
  }
};

/**
 * @swagger
 * /api/auth/get-default-vehicle:
 *   get:
 *     summary: 获取默认车辆
 *     tags: [用户]
 *     security:
 *       - bearerAuth: []
 *     responses:
 *       200:
 *         description: 获取成功
 *       404:
 *         description: 未设置默认车辆
 */
export const getDefaultVehicle = async (
  req: AuthenticatedRequest,
  res: Response
): Promise<void> => {
  try {
    const user = await User.findById(req.userId).populate('defaultVehicleId');

    if (!user) {
      res.status(404).json({
        success: false,
        message: '用户不存在',
      });
      return;
    }

    if (!user.defaultVehicleId) {
      res.status(200).json({
        success: false,
        message: '未设置默认车辆',
        data: {
          defaultVehicleId: null,
          vehicle: null,
        },
      });
      return;
    }

    res.status(200).json({
      success: true,
      message: '获取默认车辆成功',
      data: {
        defaultVehicleId: user.defaultVehicleId,
        vehicle: user.defaultVehicleId,
      },
    });
  } catch (error) {
    console.error('获取默认车辆错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误',
    });
  }
};
